<?php


namespace app\api\controller;

use app\common\model\Station as stationModel;
use app\validate\Check;
use app\validate\StationCheck;
use library\Controller;
use think\Db;
use think\Request;

class Station extends Base
{
    public function isChinese($string)
    {
        return preg_match('/[\x{4e00}-\x{9fa5}]+/u', $string);
    }

    //电站列表
    public function index(Request $request)
    {
        $param = $request->param();
        $keyword = $param['keyword'] ?? '';
        $lat = $param['lat'] ?? '';
        $lng = $param['lng'] ?? '';

        if ($keyword) {
            if ($this->isChinese($keyword)) {
                Db::table("store_search")->insert(['user_id' => $param['user_id'], 'create_at' => date('Y-m-d H:i:s'), 'keyword' => $keyword]);
            }
        }

        $where = "where  status=1 and delete_time is null and is_park=1";
        if ($keyword) {
            $where .= " and (name like '%$keyword%' or province like '%$keyword%' or city like '%$keyword%' or area like '%$keyword%') ";
        }

        $sql = "SELECT s.*,(6371 * acos (cos ( radians($lat) ) * cos( radians( s.lat ) ) * cos( radians( s.lng ) - radians($lng) ) 
+ sin ( radians($lat) ) * sin( radians( s.lat ) ) ) ) AS distance FROM store_power_station s $where ORDER BY distance asc";

        $lists = Db::query($sql);

        foreach ($lists as $k => &$v) {
            $v['range'] = sprintf('%.2f', ($v['distance']));
            if ($v['range'] > 999) {
                $v['range'] = 999;
            } else {
                $v['range'] = sprintf('%.2f', ($v['distance']));
            }

            if ($v['type'] == 1) {
                $v['type_name'] = '物业';
            }
            if ($v['type'] == 2) {
                $v['type_name'] = '个人';
            }
            if ($v['type'] == 3) {
                $v['type_name'] = '联营电站';
            }
            if ($v['type'] == 4) {
                $v['type_name'] = '非联营电站';
            }

            $v['open_name'] = $v['charge_name'] = '';

            if ($v['is_open'] == 1) {
                $v['open_name'] = '对外开放';
            }

            if ($v['is_charge'] == 1) {
                $v['charge_name'] = '停车收费';
            }

            $v['kuai_total'] = Db::table("store_device")->where(["station_id" => $v['id']])->where("is_shenhe=1")->where("delete_time is null and speed='快'")->count();
            $v['kuai_status'] = Db::table("store_device")->where(["station_id" => $v['id']])->where("is_shenhe=1")->where("delete_time is null and speed='快' and status=1")->count();
            $v['man_total'] = Db::table("store_device")->where(["station_id" => $v['id']])->where("is_shenhe=1")->where("delete_time is null and speed='慢'")->count();
            $v['man_status'] = Db::table("store_device")->where(["station_id" => $v['id']])->where("is_shenhe=1")->where("delete_time is null and speed='慢' and status=1")->count();
        }

        return $this->api_result(200, '请求成功', $lists);
    }

    //地图电站
    public function lists(Request $request, Check $check, stationModel $station)
    {
        try {
            $param = $request->param();
            $list = $station->lists($param);
            return $this->api_result(200, '请求成功', $list);
        } catch (\Exception $e) {
            return $this->api_result(400, '请求失败', []);
        }
    }


    //地图电站 筛选条件 可预约
    public function can_order()
    {
        return $this->api_result(200, '请求成功', [['label' => '请选择', 'value' => 0], ['label' => '物业', 'value' => 1], ['label' => '个人', 'value' => 2], ['label' => '联营电站', 'value' => 3]]);
    }

    //地图电站 筛选条件 不可预约
    public function no_can_order()
    {
        return $this->api_result(200, '请求成功', [['label' => '请选择', 'value' => 0], ['label' => '非联营电站', 'value' => 4]]);
    }


    //地图电站 筛选条件 车位 电桩筛选
    public function park_device_select()
    {
        return $this->api_result(200, '请求成功', [['label' => '请选择', 'value' => ''], ['label' => '车位', 'value' => 'is_park=1'], ['label' => '电桩', 'value' => 'is_power=1']]);
    }

    //功率选择
    public function rate_select()
    {

        $arr = Db::query("select rate value from store_device where is_shenhe=1 and delete_time is null group by rate");
        $array = [];
        array_push($array, ['value' => '请选择']);
        foreach ($arr as $k => &$v) {
            array_push($array, ['value' => $v['value'].'kw']);
        }

        return $this->api_result(200, '请求成功', $array);
    }

    //电站详情
    public function info(Request $request, Check $check, stationModel $station)
    {
        try {
            $param = $request->param();
            $list = $station->info($param);
            if ($list) {
                return $this->api_result(200, '请求成功', $list);
            } else {
                return $this->api_result(400, '请求失败', $param);
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '请求失败', []);
        }
    }

    //电站评论
    public function comment(Request $request)
    {
        $param = $request->param();
        $station_id = $param['id'] ?? '';
        $ping = $param['ping'] ?? '0';

        $page = $param['page'] ?? 1;
        $page = ($page - 1) * 10;
        if ($ping == 0) {
            $list = Db::table("store_station_comment")->where(['station_id' => $station_id])->order("id desc")->limit($page, 10)->select();
        } elseif ($ping == 1) {
            $list = Db::table("store_station_comment")->where(['station_id' => $station_id])->where("type=1")->order("id desc")->limit($page, 10)->select();
        } elseif ($ping == 2) {
            $list = Db::table("store_station_comment")->where(['station_id' => $station_id])->where("type=2")->order("id desc")->limit($page, 10)->select();
        } elseif ($ping == 3) {
            $list = Db::table("store_station_comment")->where(['station_id' => $station_id])->where("type=3")->order("id desc")->limit($page, 10)->select();
        } else {
            $list = Db::table("store_station_comment")->where(['station_id' => $station_id])->order("id desc")->limit($page, 10)->select();
        }
        foreach ($list as $k => &$v) {
            $v['member'] = Db::table("store_member")->where(['id' => $v['user_id']])->find();
        }
        return $this->api_result(200, '请求成功', $list);
    }


    //电站添加
    public function add(Request $request, StationCheck $check, stationModel $station)
    {
        try {
            $param = $request->param();
            $result = $check->scene('station_check')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                $msg = $station->add($param);
                if ($msg == 1) {
                    return $this->api_result(200, '请求成功', $param);
                } else {
                    return $this->api_result(400, $msg, []);
                }
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '请求失败', []);
        }
    }

    //电站修改
    public function update(Request $request, StationCheck $check, stationModel $station)
    {
        try {
            $param = $request->param();
            $result = $check->scene('station_save')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                $list = $station->station_save($param);
                if ($list == 1) {
                    return $this->api_result(200, '请求成功', $param);
                } else {
                    return $this->api_result(400, $list, $param);
                }
            }
        } catch (\Exception $e) {
            dump($e);
            return $this->api_result(400, '请求失败', []);
        }
    }

    //电站删除
    public function del(Request $request, StationCheck $check, stationModel $station)
    {
        try {
            $param = $request->param();
            $result = $check->scene('station_del')->check($param);
            if (!$result) {
                return $this->api_result(400, $check->getError(), []);
            } else {
                $list = $station->del($param);
                if ($list == 1) {
                    return $this->api_result(200, '请求成功', $param);
                } else {
                    return $this->api_result(400, $list, $param);
                }
            }
        } catch (\Exception $e) {
            return $this->api_result(400, '请求失败', []);
        }
    }


    //电站度数
    public function automatic_station()
    {
        $list = Db::table("store_power_station")->field("id")->where("delete_time is null")->select();
        foreach ($list as $k => &$v) {
            $price = 0;
            $id = $v['id'];
            $total_price = Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $id])->sum('price')+Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $id])->sum('service_price');
            $total_price2 = Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $id])->sum('price2')+Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $id])->sum('service_price2');
            $total_price3 = Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $id])->sum('price3')+Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $id])->sum('service_price3');
            $total_price4 = Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $id])->sum('price4')+Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $id])->sum('service_price4');

            $total = sprintf('%.5f', (($total_price + $total_price2 + $total_price3 + $total_price4) / 4));
            if ($total) {
                $count = Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $id])->count();
                if ($count) {
                    $price = sprintf('%.5f', $total / $count);
                }
            }

            $find['is_park'] = Db::table("store_park")->where("delete_time is null")->where(['station_id' => $v['id'], 'status' => 1])->field("id")->find();
            $find['is_power'] = Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $v['id'], 'status' => 1])->field("id")->find();
            if ($find['is_park']) {
                $is_park = 1;
            } else {
                $is_park = 0;
            }
            if ($find['is_power']) {
                $is_power = 1;
            } else {
                $is_power = 0;
            }


            $power_rate = Db::table("store_device")->where("is_shenhe=1 and delete_time is null")->where(['station_id' => $v['id']])->group("rate")->select();
            $rate = [];
            foreach ($power_rate as $kk => &$vv) {
                if (!in_array($vv['rate'], $rate)) {
                    array_push($rate, $vv['rate']);
                }
            }
            if ($rate) {
                $new_rate = implode(',', $rate);
            } else {
                $new_rate = '';
            }
            Db::table("store_power_station")->where(['id' => $v['id']])->update(['price' => $price, 'is_park' => $is_park, 'is_power' => $is_power, 'power_rate' => $new_rate]);
        }
    }


}